package com.wugui.datatx.core.glue.impl;

import cn.hutool.core.util.StrUtil;
import com.wugui.datatx.core.executor.impl.JobSpringExecutor;
import com.wugui.datatx.core.glue.GlueFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * @author xuxueli 2018-11-01
 */
@Slf4j
public class SpringGlueFactory extends GlueFactory {

  /**
   * inject action of spring
   *
   * @param instance
   */
  @Override
  public void injectService(Object instance) {
    if (instance == null) {
      return;
    }

    if (JobSpringExecutor.getApplicationContext() == null) {
      return;
    }

    Field[] fields = instance.getClass().getDeclaredFields();
    for (Field field : fields) {
      if (Modifier.isStatic(field.getModifiers())) {
        continue;
      }

      Object fieldBean = null;
      // with bean-id, bean could be found by both @Resource and @Autowired, or bean could only be
      // found by @Autowired

      if (AnnotationUtils.getAnnotation(field, Resource.class) != null) {
        try {
          Resource resource = AnnotationUtils.getAnnotation(field, Resource.class);
          if (StrUtil.isNotBlank(resource.name())) {
            fieldBean = JobSpringExecutor.getApplicationContext().getBean(resource.name());
          } else {
            fieldBean = JobSpringExecutor.getApplicationContext().getBean(field.getName());
          }
        } catch (Exception ignored) {
        }
        if (fieldBean == null) {
          fieldBean = JobSpringExecutor.getApplicationContext().getBean(field.getType());
        }
      } else if (AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
        Qualifier qualifier = AnnotationUtils.getAnnotation(field, Qualifier.class);
        if (qualifier != null && StrUtil.isNotBlank(qualifier.value())) {
          fieldBean = JobSpringExecutor.getApplicationContext().getBean(qualifier.value());
        } else {
          fieldBean = JobSpringExecutor.getApplicationContext().getBean(field.getType());
        }
      }

      if (fieldBean != null) {
        field.setAccessible(true);
        try {
          field.set(instance, fieldBean);
        } catch (IllegalArgumentException | IllegalAccessException e) {
          log.error(e.getMessage(), e);
        }
      }
    }
  }
}
